import {defineStore} from "pinia"
import {computed, ref} from "vue";
import {ElMessage} from "element-plus";
import {cartListService, delCartService, insertCartService, modifyCartService} from "@/apis/shoppingCart";


export const useCartStore = defineStore('shopcar', () => {

    const cartList = ref([])

    const updateCart = async () => {
        const res = await cartListService()
        console.log(res.data)
        cartList.value = res.data
    }

    const addCart = async (books) => {
        const {id, count} = books
        await insertCartService({id, count})
        await updateCart()
        ElMessage.success('加入购物车成功！')
    }

    // delete books
    const delCart = async (id) => {
        // 调用接口
        await delCartService(id)
        await updateCart()
        ElMessage.success('删除商品成功！')
    }

    // clear when logout
    const clearCart = () => {
        cartList.value = []
    }

    const countChange = async (id) => {
        for (const item of cartList.value) {
            await modifyCartService(item)
        }
    }

    const singleCheck = async (id, selected) => {
        const item = cartList.value.find((item) => item.id === id)
        item.selected = selected
        await modifyCartService(item)
    }

    const allCheck = async (selected) => {
        cartList.value.forEach(item => item.selected = selected)
        for (const item of cartList.value) {
            await modifyCartService(item)
        }
    }


    const numCount = computed(() => cartList.value.reduce((a, c) => a + parseInt(c.count), 0))

    const priceCount = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))

    const checkAll = computed(() => cartList.value.every((item) => item.selected))

    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + parseInt(c.count), 0))

    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))

    return {
        cartList,
        addCart,
        delCart,
        singleCheck,
        allCheck,
        clearCart,
        updateCart,
        countChange,
        numCount,
        priceCount,
        checkAll,
        selectedCount,
        selectedPrice
    }
}, {
    persist: true
})